package com.my.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.my.model.User;

@Controller
@RequestMapping("/user")
public class UserAction extends mybaseAction{
    @RequestMapping("/toAddUser")
    public String toAddUser(HttpServletRequest request) {
        return "/addUser";
    }
    @RequestMapping("/addUser")
    public String addUser(User user) {
    	JSONObject param=new JSONObject();
    	param.put("id", user.getId());
    	param.put("userName", user.getUserName());
        prdDbService.modify("userMapper.save", param);
        return "redirect:/user/getAllUser";
    }
    @RequestMapping("/updateUser")
    public String updateUser(User user) throws IOException{
    	boolean flag=false;
		JSONObject param=new JSONObject();
    	param.put("id", user.getId());
    	param.put("userName", user.getUserName());
    	try {
            prdDbService.modify("userMapper.update", param);
            flag=true;
		} catch (Exception e) {
			e.printStackTrace();
		}
        if (flag) {
            request.setAttribute("user", user);
            return "redirect:/user/getAllUser";
        } else {
            return "/error";
        }
    }
    @RequestMapping("/delUser")
    public void delUser(int id) throws IOException {
        String result = "{\"result\":\"error\"}";
        JSONObject param=new JSONObject();
    	param.put("id", id);
    	prdDbService.modify("userMapper.delete", param);
		result = "{\"result\":\"success\"}";
        response.setContentType("application/json");
        try {
            PrintWriter out = response.getWriter();
            out.write(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @RequestMapping("/getUser")
    public String getUser(String id) {
    	JSONObject param=new JSONObject();
     	param.put("id", id);
     	Map<String, Object>  data = prdDbService.selectOne("userMapper.findById", param);
     	if(data!=null){
        	User user =new User();
        	user.setId((Integer) data.get("ID"));
        	user.setUserName((String) data.get("USERNAME"));
            request.setAttribute("user", user);
            return "/editUser";
     	}else{
     		return "/error";
     	}
    }
    @RequestMapping("/getAllUser")
    public String getAllUser() {
    	List<Map<String, Object>> data = prdDbService.selectList("userMapper.findAll");
        request.setAttribute("userList", data);
        return "/allUser";
    }

}